layui.define(['index', 'form', 'table', 'laypage', 'layedit', 'laydate', '$http', 'zmnUtils', 'layer', 'zmnSelect','element'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var laypage = layui.laypage;
    var layedit = layui.layedit;
    var laydate = layui.laydate;
    var $http = layui.$http;
    var zmnUtils = layui.zmnUtils;
    var configObj = json.obj;
    var robOrderObj = json.robOrderObj;
    var engineerList =json.engineerList;
    let zmnSelect = layui.zmnSelect;
    var element = layui.element;

    var cityId;
    var cityName="";

    //判断是否点击添加规则按钮
    var sum =1;
    dealRobOrderConfigData(robOrderObj)
    // 点击取消
    $("button#cancel").click(function () {
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);//关闭当前页
    });
    //添加规则下单时间段、预约时间段、剔除渠道、剔除品类、工程师类型可能会出现多个，放在数组中后续取值

    // 渠道列表
    zmnSelect.selectlChannelOnesTwos({
        channelOneSelectId: 'channelOneIdList',
        channelTwoSelectId: 'channelTwoIdList',
    }, {
        channelOneSelectId: {
            maxCount: 100, //下拉框中的最多选项数量
            selectedValues:robOrderObj.robOrderRelationList.length>0&&robOrderObj.robOrderRelationList[0].firstLevelChannel!=null
                            ?robOrderObj.robOrderRelationList[0].firstLevelChannel.split(","):[],
            remote: {
                events: {
                    extendParams: function () {
                        return {status: 2}
                    },
                }
            },
            events: {
                changed: function (values) {
                    console.log("========channelOneIdList==========");
                    console.log("已选中的值:" + values);
                }
            }
        },
        channelTwoSelectId: {
            maxCount: 100, //下拉框中的最多选项数量
            selectedValues:robOrderObj.robOrderRelationList.length>0&&robOrderObj.robOrderRelationList[0].secondLevelChannel?
                            robOrderObj.robOrderRelationList[0].secondLevelChannel.split(","):[],
            remote: {
                events: {
                    extendParams: function () {
                        return {status: 2}
                    },
                }
            },
            events: {
                changed: function (values) {
                    console.log("========channelTwoIdList==========");
                    console.log("已选中的值:" + values);
                }
            }
        }
    });

    //服务分类列表
    zmnSelect.selectlEcProdCategories({
        servCategSelectId: "ecServCategId",
        ecCategOneSelectId: "ecServCategOneIdList",
    }, {
        servCategSelectId: {
            selectedValues: robOrderObj.robOrderRelationList.length>0
            &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList.length>0
            &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList[0].serviceClassification!=null
                ?robOrderObj.robOrderRelationList[0].robOrderRelationProductList[0].serviceClassification.split(","):[],
            remote: {
                limitPermit: false,
            },
            events: {
                changed(values) {
                    console.log("==========ecServCategId=========");
                    console.log("已选中的值:" + values);
                }
            }
        },
        ecCategOneSelectId: {
            selectedValues: robOrderObj.robOrderRelationList.length>0
            &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList.length>0
            &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList[0].firstLevelProduct!=null
                ?robOrderObj.robOrderRelationList[0].robOrderRelationProductList[0].firstLevelProduct.split(","):[],
            remote: {
                limitPermit: false,
            },
            events: {
                changed(values) {
                    console.log("==========ecServCategOneIdList=========");
                    console.log("已选中的值:" + values);
                }
            }
        },
    });




    form.verify({
        percentVal: function (value, item) {
            if (value !== "") {
                if (Number(value) < 0) {
                    return '占比数值不能小于0';
                }
                if (Number(value) > 100) {
                    return '占比数值不能大于100';
                }
            }
        },
        reworkLimit: function (value, item) {
            if (value !== "" && value !== '0') {
                if (Number(value) < 0) {
                    return '最大返修单量不能小于0';
                }
                if (Number(value) > 1000000) {
                    return '最大返修单量不能大于1000000';
                }
                var r = /^[1-9]\d*$/;
                if (!r.test(value)) {
                    return '只能输入正整数，请重新输入';
                }
            }
        },
        numberLimit: function (value, item) {
            var r = /^[1-9]\d*$/;
            if (value != "" && !r.test(value)) {
                return '只能输入正整数，请重新输入';
            }
        }
    });
    $(document).on('click', '#addRules', function () {
        //新增规则
        let node = initRuleNode("", "", "","","");
        $("#dynamic").append(node);
        //新增再次渲染时间插件
        drawTimePlug()
        //渲染下拉框
        drawSelect('add');
        $("#addRules").hide();
        form.render();
    });
    $(document).on('click', '.delete', function () {
        $(this).closest('.layui-current-row').remove();
        //删除规则，字段id变化
        $("#addRules").show();
        //删除远端缓存下拉框id
        var deleteSelects = ["channelOneIdList1","channelTwoIdList1","ecServCategId2","ecServCategOneIdList2","ecServCategId3","ecServCategOneIdList3"];
        zmnSelect.deleteXmSelects(deleteSelects);
    });
    $(document).on('click', '.deleteProduct', function () {
        $(this).closest('.layui-product-row').remove();
        //删除规则，字段id变化
        $(".addProducts").show();
        var deleteSelects = ["ecServCategId1","ecServCategOneIdList1"];
        zmnSelect.deleteXmSelects(deleteSelects);
    });

    $(document).on('click', '.deleteProduct1', function () {
        $(this).closest('.layui-product-row1').remove();
        //删除规则，字段id变化
        $(".addProducts1").show();
        //删除远端缓存下拉框id
        var deleteSelects = ["ecServCategId3","ecServCategOneIdList3"];
        zmnSelect.deleteXmSelects(deleteSelects);

    });

    $(document).on('click', ".addProducts", function () {
            //新增品类
            let baseHtml = addProductsFunc();
            $(".productFlag").append(baseHtml);
            //再次渲染下拉框样式
            drawSelect1();
            $(".addProducts").hide();
    });

    function addProductsFunc(){
        let baseHtml =  '<div class="layui-card layui-product-row">\n' +
            '           <div class="layui-row">\n' +
            '               <div class="layui-col-sm10 layui-form">\n' +
            '                  <div class="layui-form-item" >\n' +
            '            <label class="layui-form-label "></label>\n' +
            '                      <div class="layui-input-inline" >\n' +
            '                          <div id="ecServCategId1"></div>\n' +
            '                      </div>\n' +
            '                      <div class="layui-input-inline" >\n' +
            '                          <div id="ecServCategOneIdList1"></div>\n' +
            '                      </div>\n' +
            '                  </div>\n' +
            '               </div>\n' +
            '           </div>\n' +
            '<div class="layui-row">\n' +
            '    <div class="layui-col-sm10 layui-form">\n' +
            '        <div class="layui-form-item" style="margin-top: 10px">\n' +
            '           <div   className="layui-input-block" > \n' +
            '                <a href="javascript:void(0)" class="deleteProduct" data-method="deleteProduct" style="text-decoration:underline;color: #00a0e9">删除</a>\n' +
            '           </div>\n' +
            '        </div>\n' +
            '    </div>\n' +
            '    </div>\n' +
            '</div>';
        return baseHtml;
    }

    $(document).on('click', '.addProducts1', function () {
       let baseHtml = addProductsFunc1();
        $('.productFlag1').append(baseHtml);

        //再次渲染下拉框样式
        drawSelect3();
        form.render();
        $(".addProducts1").hide();
    });

    function addProductsFunc1(){
        let baseHtml =  '<div class="layui-card layui-product-row1">\n' +
            '           <div class="layui-row">\n' +
            '               <div class="layui-col-sm10 layui-form">\n' +
            '                  <div class="layui-form-item" >\n' +
            '            <label class="layui-form-label "></label>\n' +
            '                      <div class="layui-input-inline" >\n' +
            '                          <div id="ecServCategId3"></div>\n' +
            '                      </div>\n' +
            '                      <div class="layui-input-inline" >\n' +
            '                          <div id="ecServCategOneIdList3"></div>\n' +
            '                      </div>\n' +
            '                  </div>\n' +
            '               </div>\n' +
            '<div class="layui-row">\n' +
            '    <div class="layui-col-sm10 layui-form">\n' +
            '        <div class="layui-form-item" style="margin-top: 10px">\n' +
            '           <div   className="layui-input-block" > \n' +
            '                <a href="javascript:void(0)" class="deleteProduct1" data-method="deleteProduct1" style="text-decoration:underline;color: #00a0e9">删除</a>\n' +
            '           </div>\n' +
            '        </div>\n' +
            '    </div>\n' +
            '    </div>\n' +
            '</div>';
        return baseHtml;
    }




    function drawTimePlug(){
        lay('.orderTimeStr1').each(function () {
            laydate.render({
                elem: this,
                type: 'time'
                , range: '~'
                , format: 'HH:mm'
                , trigger: 'click'
            });
        });
        lay('.appointmentTimeStr1').each(function () {
            laydate.render({
                elem: this,
                type: 'time'
                , range: '~'
                , format: 'HH:mm'
                , trigger: 'click'
            });
        });
        lay('.robOrderTimeStr1').each(function () {
            laydate.render({
                elem: this,
                type: 'time'
                , range: '~'
                , format: 'HH:mm'
                , trigger: 'click'
            });
        });
    }

    function drawSelect(flag){
        var selectedValues1=[];
        var selectedValues2=[];
        var selectedValues3=[];
        var selectedValues4=[];
        if(flag=='edit'){
            selectedValues1 =robOrderObj.robOrderRelationList.length>1&&robOrderObj.robOrderRelationList[1].firstLevelChannel!=null
                                ?robOrderObj.robOrderRelationList[1].firstLevelChannel.split(","):[];
            selectedValues2 =robOrderObj.robOrderRelationList.length>1&&robOrderObj.robOrderRelationList[1].secondLevelChannel!=null
                                ?robOrderObj.robOrderRelationList[1].secondLevelChannel.split(","):[];
            selectedValues3 =robOrderObj.robOrderRelationList.length>1
                                &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList.length>0
                                &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList[0].serviceClassification!=null
                                    ?robOrderObj.robOrderRelationList[1].robOrderRelationProductList[0].serviceClassification.split(","):[];
            selectedValues4 = robOrderObj.robOrderRelationList.length>1
                                &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList.length>0
                                &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList[0].firstLevelProduct!=null
                                    ?robOrderObj.robOrderRelationList[1].robOrderRelationProductList[0].firstLevelProduct.split(","):[];
        }
        //再次渲染下拉框样式
        zmnSelect.selectlChannelOnesTwos({

            channelOneSelectId: "channelOneIdList1",
            channelTwoSelectId: "channelTwoIdList1",
        }, {
            channelOneSelectId: {
                maxCount: 100, //下拉框中的最多选项数量
                selectedValues:selectedValues1,
                remote: {
                    events: {
                        extendParams: function () {
                            return {status: 2}
                        },
                    }
                },
                events: {
                    changed: function (values) {
                        console.log("========channelOneIdList2==========");
                        console.log("已选中的值:" + values);
                    }
                }
            },
            channelTwoSelectId: {
                maxCount: 100, //下拉框中的最多选项数量
                selectedValues:selectedValues2,
                remote: {
                    events: {
                        extendParams: function () {
                            return {status: 2}
                        },
                    }
                },
                events: {
                    changed: function (values) {
                        console.log("========channelTwoIdList2==========");
                        console.log("已选中的值:" + values);
                    }
                }
            }
        });
        zmnSelect.selectlEcProdCategories({
            servCategSelectId: "ecServCategId2",
            ecCategOneSelectId: "ecServCategOneIdList2",
        }, {
            servCategSelectId: {
                selectedValues: selectedValues3,
                remote: {
                    // limitPermit: false,
                },
                events: {
                    changed(values) {
                        console.log("==========ecServCategId=========");
                        console.log("已选中的值:" + values);
                    }
                }
            },
            ecCategOneSelectId: {
                selectedValues: selectedValues4,
                remote: {
                    // limitPermit: false,
                },
                events: {
                    changed(values) {
                        console.log("==========ecServCategOneIdList=========");
                        console.log("已选中的值:" + values);
                    }
                }
            },
        });
    };

    function drawSelect1(){
        zmnSelect.selectlEcProdCategories({
            servCategSelectId: "ecServCategId1",
            ecCategOneSelectId: "ecServCategOneIdList1",
        }, {
            servCategSelectId: {
                selectedValues:  robOrderObj.robOrderRelationList.length>0
                &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList.length>1
                &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList[1].serviceClassification!=null
                    ?robOrderObj.robOrderRelationList[0].robOrderRelationProductList[1].serviceClassification.split(","):[],
                remote: {
                     limitPermit: true,
                },
                events: {
                    changed(values) {
                        console.log("==========ecServCategId=========");
                        console.log("已选中的值:" + values);
                    }
                }
            },
            ecCategOneSelectId: {
                selectedValues: robOrderObj.robOrderRelationList.length>0
                &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList.length>1
                &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList[1].firstLevelProduct!=null
                    ?robOrderObj.robOrderRelationList[0].robOrderRelationProductList[1].firstLevelProduct.split(","):[],
                remote: {
                    // limitPermit: false,
                },
                events: {
                    changed(values) {
                        console.log("==========ecServCategOneIdList=========");
                        console.log("已选中的值:" + values);
                    }
                }
            },
        });
    }
    function  drawSelect3(){
        zmnSelect.selectlEcProdCategories({
            servCategSelectId: "ecServCategId3",
            ecCategOneSelectId: "ecServCategOneIdList3",
        }, {
            servCategSelectId: {
                selectedValues:robOrderObj.robOrderRelationList.length>1
                &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList.length>1
                &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList[1].serviceClassification!=null
                    ?robOrderObj.robOrderRelationList[1].robOrderRelationProductList[1].serviceClassification.split(","):[],
                remote: {
                    // limitPermit: false,
                },
                events: {
                    changed(values) {
                        console.log("==========ecServCategId=========");
                        console.log("已选中的值:" + values);
                    }
                }
            },
            ecCategOneSelectId: {
                selectedValues: robOrderObj.robOrderRelationList.length>1
                &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList.length>1
                &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList[1].firstLevelProduct!=null
                    ?robOrderObj.robOrderRelationList[1].robOrderRelationProductList[1].firstLevelProduct.split(","):[],
                remote: {
                    // limitPermit: false,
                },
                events: {
                    changed(values) {
                        console.log("==========ecServCategOneIdList=========");
                        console.log("已选中的值:" + values);
                    }
                }
            },
        });
    }




    function initRuleNode(orderTimeVal, appointmentTimeVal, robOrderTimeVal,engineerTypeVal,relationId) {

        let baseHtml = '<div class="layui-card layui-current-row"><hr><hr/>\n' +
            '        <div class="layui-card-header layui-select-row">工单设置：</span></div>\n' +
            '            <div class="layui-row" style="display: none">\n' +
            '                <div class="layui-col-sm10 layui-form">\n' +
            '                    <div class="layui-form-item">\n' +
            '                        <label class="layui-form-label layui-form-required">relationId:</label>\n' +
            '                        <div class="layui-input-inline">\n' +
            '                            <input  type="text" value="' + relationId + '" name="relationId1" \n' +
            '                                   class="layui-input"/>\n' +
            '                        </div>\n' +
            '                    </div>\n' +
            '                </div>\n' +
            '            </div>\n'+
            '        <div class="layui-row">\n' +
            '            <div class="layui-col-sm10 layui-form">\n' +
            '                <div class="layui-form-item">\n' +
            '                    <label class="layui-form-label">下单时间段:</label>\n' +
            '                    <div class="layui-input-inline">\n' +
            '                        <input value="' + orderTimeVal + '" type="text"\n' +
            '                               name="orderTimeStr1"\n' +
            '                               class="layui-input orderTimeStr1"/>\n' +
            '                    </div>\n' +
            '                </div>\n' +
            '            </div>\n' +
            '        </div>\n' +
            '        <div class="layui-row">\n' +
            '            <div class="layui-col-sm10 layui-form">\n' +
            '                <div class="layui-form-item">\n' +
            '                    <label class="layui-form-label ">预约时间段:</label>\n' +
            '                    <div class="layui-input-inline">\n' +
            '                        <input value="' + appointmentTimeVal + '" type="text"\n' +
            '                               name="appointmentTimeStr1"\n' +
            '                               class="layui-input appointmentTimeStr1"/>\n' +
            '                    </div>\n' +
            '                </div>\n' +
            '            </div>\n' +
            '        </div>\n' +
            '<div class="layui-row">\n' +
            '    <div classN="layui-col-sm10 layui-form">\n' +
            '        <div class="layui-form-item layui-form"  lay-filter="one">\n' +
            '            <label class="layui-form-label ">剔除渠道：</label>\n' +
            '            <div class="layui-input-inline" >\n' +
            '                <div id="channelOneIdList1"  ></div>\n' +
            '            </div>\n' +
            '            <div class="layui-input-inline">\n' +
            '                <div id="channelTwoIdList1" ></div>\n' +
            '            </div>\n' +
            '        </div>\n' +
            '    </div>\n' +
            '</div>\n' +
            '<div class="layui-row">\n' +
            '    <div classN="layui-col-sm10 layui-form">\n' +
            '        <div class="layui-form-item layui-form"  lay-filter="one">\n' +
            '            <label class="layui-form-label ">剔除品类：</label>\n' +
            '            <div class="layui-input-inline" >\n' +
            '                <div id="ecServCategId2" ></div>\n' +
            '            </div>\n' +
            '            <div class="layui-input-inline">\n' +
            '                <div id="ecServCategOneIdList2" ></div>\n' +
            '            </div>\n' +
            '        </div>\n' +
            '    </div>\n' +
            '  <div  class="productFlag1"></div>\n' +
            '            <div class="layui-input-block">\n' +
            '                <a  href="javascript:void(0)"  class="addProducts1"\n' +
            '                   style="text-decoration:underline;color: #00a0e9">+添加</a>\n' +
            '            </div>\n' +
            '</div>\n' +
            '        <div class="layui-card-header">工程师设置：</span></div>\n' +
            '        <div class="layui-row">\n' +
            '            <div class="layui-col-sm10 layui-form">\n' +
            '                <div class="layui-form-item" style="margin-top: 10px">\n' +
            '                    <label class="layui-form-label layui-form-required">工程师类型:</label>\n' +
            '                    <div class="layui-input-inline">\n' +
            '                        <select  name="engineerType1" lay-verify="required"\n' +
            '                                lay-search=""\n' +
            '                                 autocomplete="off">\n' +drawList(engineerTypeVal)+
            '                        </select>\n' +
            '                    </div>\n' +
            '                    <div class="layui-form-mid layui-word-aux">当仅有此类型工程师时，工单将按抢单方式分配</div>\n' +
            '                </div>\n' +
            '            </div>\n' +
            '        </div>\n' +
            '<div className="layui-card-header">抢单时间:</div>\n' +
            '        <div class="layui-row">\n' +
            '            <div class="layui-col-sm10 layui-form">\n' +
            '                <div class="layui-form-item">\n' +
            '                    <label class="layui-form-label layui-form-required">抢单时间:</label>\n' +
            '                    <div class="layui-input-inline">\n' +
            '                        <input  value="' + robOrderTimeVal + '" lay-verify="required" type="text"\n' +
            '                               name="robOrderTimeStr1"\n' +
            '                               class="layui-input robOrderTimeStr1"/>\n' +
            '                    </div>\n' +
            '                </div>\n' +
            '            </div>\n' +
            '        </div>\n' +
            '        <div class="layui-row">\n' +
            '            <div class="layui-col-sm10 layui-form">\n' +
            '                <div class="layui-form-item" style="margin-top: 10px">\n' +
            '                    <div   className="layui-input-block" >\n' +
            '                <a href="javascript:void(0)" class="delete" data-method="delete" style="text-decoration:underline;color: #00a0e9">删除规则</a>\n' +
            '                    </div>\n' +
            '                </div>\n' +
            '            </div>\n' +
            '        </div>\n' +
            '    </div>';
        return baseHtml;
    }

    function drawList(engineerTypeVal){
        var optionHtml='';
        if(engineerTypeVal==""){
            optionHtml = '<option value="">请选择工程师</option>'
        }
        for (var i = 0; i < engineerList.length; i++) {
            if (engineerList[i]['key']===engineerTypeVal) {
                optionHtml += '<option value="' + engineerList[i]['key'] + '" selected>' + engineerList[i]['value'] + '</option>';
            } else {
                optionHtml += '<option value="' + engineerList[i]['key'] + '">' + engineerList[i]['value'] + '</option>';
            }

        }
        return optionHtml;
    }


    // 是否为正整数
    function isPositiveInteger(number) {
        var re = /^[0-9]\d*$/;
        return re.test(number)
    }
    //后者时间大于前者
    function checkDate(t1,t2){
        var date = new Date();
        var a = t1.split(":");
        var b = t2.split(":");
        if (parseInt(a[0])>parseInt(b[0])) {
            return true;
        }
        if (parseInt(a[0])==parseInt(b[0])&&parseInt(a[1])>=parseInt(b[1])) {
            return true;
        }
        return false;
    }

    // 比较两个时间的先后
    function compareDate(t1, t2) {
        var date = new Date();
        var a = t1.split(":");
        if (a[0] < 0 || a[0] > 23) {
            return true;
        }
        if (a[1] < 0 || a[1] > 59) {
            return true;
        }
        var b = t2.split(":");
        if (b[0] < 0 || b[0] > 23) {
            return true;
        }
        if (b[1] < 0 || b[1] > 59) {
            return true;
        }
        return date.setHours(a[0], a[1]) > date.setHours(b[0], b[1]);
    }

    form.on('submit(zmn-rob-order-form-submit)', function (obj) {
        var data = obj.field;
        data.bizType = configObj.bizType;
        data.distributeWay=configObj.distributeWay;
        let robOrderRelationList = [];
        let find = $("#dynamic").find(".layui-current-row");
        let robOrderRelationProductList1 = [];

                if(obj.field["ecServCategId"]!=""&&obj.field["ecServCategId"]!=null&&obj.field["ecServCategId"]!=undefined){
                    let robOrderRelationProduct = {
                        relationProductId: robOrderObj.robOrderRelationList.length>0
                                             &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList.length>0
                                             &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList[0].relationProductId!=null?
                                                robOrderObj.robOrderRelationList[0].robOrderRelationProductList[0].relationProductId:null,
                        serviceClassification:obj.field["ecServCategId"],
                        firstLevelProduct:obj.field["ecServCategOneIdList"],
                    }
                    robOrderRelationProductList1.push(robOrderRelationProduct);
                }
               if(obj.field["ecServCategId1"]!=""&&obj.field["ecServCategId1"]!=null&&obj.field["ecServCategId1"]!=undefined){
                   let  robOrderRelationProduct = {
                       relationProductId: robOrderObj.robOrderRelationList.length>0
                       &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList.length>1
                       &&robOrderObj.robOrderRelationList[0].robOrderRelationProductList[1].relationProductId!=null?
                           robOrderObj.robOrderRelationList[0].robOrderRelationProductList[1].relationProductId:null,
                       serviceClassification:obj.field["ecServCategId1"],
                       firstLevelProduct:obj.field["ecServCategOneIdList1"],
                   }
                   if(obj.field["ecServCategId1"]==obj.field["ecServCategId"]){
                       layer.msg('同一个规则组服务分类不能重复!');
                       return false;
                   }
                   robOrderRelationProductList1.push(robOrderRelationProduct);
               }


        let robOrderRelation = {
            relationId: obj.field["relationId"],
            orderTimeStr: obj.field["orderTimeStr"],
            appointmentTimeStr:obj.field["appointmentTimeStr"],
            robOrderTimeStr: obj.field["robOrderTimeStr"],
            engineerType:obj.field["engineerType"],
            firstLevelChannel:obj.field["channelOneIdList"],
            secondLevelChannel:obj.field["channelTwoIdList"],
            robOrderRelationProductList:robOrderRelationProductList1

        };
        robOrderRelationList.push(robOrderRelation);

        let robOrderRelationProductList2 = [];

                if(obj.field["ecServCategId2"]!=""&&obj.field["ecServCategId2"]!=null&&obj.field["ecServCategId2"]!=undefined){
                    let robOrderRelationProduct = {
                        relationProductId: robOrderObj.robOrderRelationList.length>1
                        &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList.length>0
                        &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList[0].relationProductId!=null?
                            robOrderObj.robOrderRelationList[1].robOrderRelationProductList[0].relationProductId:null,
                        serviceClassification:obj.field["ecServCategId2"],
                        firstLevelProduct:obj.field["ecServCategOneIdList2"],
                    }
                    robOrderRelationProductList2.push(robOrderRelationProduct);
                }
                if(obj.field["ecServCategId3"]!=""&&obj.field["ecServCategId3"]!=null&&obj.field["ecServCategId3"]!=undefined){
                   let robOrderRelationProduct = {
                       relationProductId: robOrderObj.robOrderRelationList.length>1
                       &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList.length>1
                       &&robOrderObj.robOrderRelationList[1].robOrderRelationProductList[1].relationProductId!=null?
                           robOrderObj.robOrderRelationList[1].robOrderRelationProductList[1].relationProductId:null,
                       serviceClassification:obj.field["ecServCategId3"],
                       firstLevelProduct:obj.field["ecServCategOneIdList3"],
                    }
                    if(obj.field["ecServCategId2"]==obj.field["ecServCategId3"]){
                        layer.msg('同一个规则组服务分类不能重复!');
                        return false;
                    }
                    robOrderRelationProductList2.push(robOrderRelationProduct);
                }
        let compareOrderTime = false;
        let compareRobOrderTime = false;
        find.each(function (index, value) {
            let orderTimeStr = $(value).find("[name='orderTimeStr1']").val();
            if(orderTimeStr===(obj.field["orderTimeStr"])){
                compareOrderTime = true;
            }

            let appointmentTimeStr = $(value).find("[name='appointmentTimeStr1']").val();
            let robOrderTimeStr = $(value).find("[name='robOrderTimeStr1']").val();
            if( obj.field["robOrderTimeStr"]===(robOrderTimeStr)){
                compareRobOrderTime =true;
            }
            let relationId = $(value).find("[name='relationId1']").val();
            let engineerType = $(value).find("[name='engineerType1']").val();
            let robOrderRelation = {
                relationId: relationId,
                orderTimeStr: orderTimeStr,
                appointmentTimeStr:appointmentTimeStr,
                robOrderTimeStr: robOrderTimeStr,
                engineerType:engineerType,
                firstLevelChannel:obj.field["channelOneIdList1"],
                secondLevelChannel:obj.field["channelTwoIdList1"],
                robOrderRelationProductList:robOrderRelationProductList2
            };
            robOrderRelationList.push(robOrderRelation);
        });
        if(compareOrderTime){
            layer.msg('各规则的下单时间不可重合!');
            return false;
        }
        if(compareRobOrderTime){
            layer.msg('各规则的抢单时间不可重合!');
            return false;
        }
        data.robOrderRelationList=robOrderRelationList;
        //目前仅针对啄木鸟平台
        data.plat=10;
        data.provinceId=data.robOrderProvinceId;
        data.cityId=data.robOrderCityId;
        data.provinceName = robOrderProvince==undefined?"":robOrderProvince.getValue()[0].name;
        data.cityName = robOrderCity==undefined?"":robOrderCity.getValue()[0].name;

        let checkOrderTime = false;
        let checkAppointmentTime = false;
        let checkRobOrderTime = false;
        if(robOrderRelationList!=null&&robOrderRelationList.length>0){

            robOrderRelationList.forEach(item => {
                //校验时间
                if(item.orderTimeStr!=""&&(checkDate(item.orderTimeStr.split("~")[0],item.orderTimeStr.split("~")[1]))){

                    checkOrderTime = true;
                }
                if(item.appointmentTimeStr!=""&&(checkDate(item.appointmentTimeStr.split("~")[0],item.appointmentTimeStr.split("~")[1]))){
                    checkAppointmentTime = true;
                }
                if(item.robOrderTimeStr!=""&&(checkDate(item.robOrderTimeStr.split("~")[0],item.robOrderTimeStr.split("~")[1]))){
                    checkRobOrderTime =true;
                }
            });
        }
        // if(checkOrderTime){
        //     layer.msg('下单结束时间必须大于开始时间!');
        //     return false;
        // }
        // if(checkAppointmentTime){
        //     layer.msg('预约结束时间必须大于开始时间!');
        //     return false;
        // }
        // if(checkRobOrderTime){
        //     layer.msg('抢单结束时间必须大于开始时间!');
        //     return false;
        // }

        var url = "";
        //configId为空是新增，先将数据存入缓存；configId不为空走更新，直接写入数据库
        if(robOrderObj.configId==null||robOrderObj.configId==undefined||robOrderObj.configId==""){
            url = "/orderconfig/distribute/plat/setRobOrderConfigDataToRedis";
            $http.save(url, data).then(function () {
                zmnUtils.layui.toastSuccess('成功', function () {
                    //城市id信息改为全局变量，最后提交使用
                    cityId = data.cityId;
                    cityName = data.cityName;

                    //切换到：派单管理
                    element.tabChange('changeSecondTab', 'sendOrderId');
                })
            }, function (msg) {
                zmnUtils.layui.toastError(msg);
            });
        }else{
            data.configId=robOrderObj.configId;
            url ="/orderconfig/distribute/plat/robOrder/modifyOrInsert"
            $http.save(url, data).then(function () {
                zmnUtils.layui.toastSuccess('成功', function () {
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                    window.parent.location.reload();
                })
            }, function (msg) {
                zmnUtils.layui.toastError(msg);
            });
        }


        return false;

    });

// 保存服务商信息
    form.on('submit(zmn-form-submit)', function (obj) {

        var data = obj.field;
        data.bizType = configObj.bizType;

        // 时间格式校验
        let autoTimeStr = data.autoTimeStr;
        let timeArr = autoTimeStr.split(' ~ ');
        if (compareDate(timeArr[0], timeArr[1])) {
            layer.msg('时间格式不正确!');
            return false;
        }
        let roundsEnable = data.roundsEnable;
        let nonDirectCount = data.nonDirectCount;
        let directSaleCount = data.directSaleCount;
        if (roundsEnable == "on") {
            data.roundsEnable = 2;
            if (nonDirectCount == "" || directSaleCount == "") {
                layer.msg("轮次开关开启，比例数值必填", {"icon": 2});
                return false;
            }
        } else {
            data.roundsEnable = 1;
        }
        let distributeWeightRelationList = [];
        let checkNan = false;
        let checkTotal = false;
        configObj.distributeWeightRelationList.forEach((item) => {
            // 非法字符检测
            if (isNaN(parseInt(item.distanceWeight)) || isNaN(parseInt(item.handlerWeight)) ||
                isNaN(parseInt(item.distributeNewCount)) ||
                isNaN(parseInt(item.serveScore)) || isNaN(parseInt(item.datumOrderHourRatio)) ||
                isNaN(parseInt(item.starLevelScoreWeight))) {
                checkNan = true;
            }
            // 正整数检测
            if (!isPositiveInteger(item.distanceWeight) || !isPositiveInteger(item.handlerWeight) ||
                !isPositiveInteger(item.distributeNewCount) ||
                !isPositiveInteger(item.serveScore) || !isPositiveInteger(item.datumOrderHourRatio) ||
                !isPositiveInteger(item.starLevelScoreWeight)) {
                checkNan = true;
            }
            if ((parseInt(item.distanceWeight) + parseInt(item.handlerWeight) +
                parseInt(item.distributeNewCount) + parseInt(item.serveScore) +
                parseInt(item.datumOrderHourRatio) + parseInt(item.starLevelScoreWeight)
            ) !== 100) {
                checkTotal = true;
            }
            let distributeWeightRelation = {
                relationId: parseInt(item.relationId),
                distanceWeight: parseInt(item.distanceWeight),
                handlerWeight: parseInt(item.handlerWeight),
                distributeNewCount: parseInt(item.distributeNewCount),
                serveScore: parseInt(item.serveScore),
                datumOrderHourRatio: parseInt(item.datumOrderHourRatio),
                starLevelScoreWeight: parseInt(item.starLevelScoreWeight),
                weightType: parseInt(item.weightType),
                distributeApplication: parseInt(item.distributeApplication),
                distributeConfigId: parseInt(item.distributeConfigId),
            }
            distributeWeightRelationList.push(distributeWeightRelation);
        });
        if (checkNan) {
            layer.msg('权重占比必须为0或正整数!');
            return false;
        }
        if (checkTotal) {
            layer.msg('权重占比之和必须等于100%');
            return false;
        }
        data.distributeWeightRelationList = distributeWeightRelationList;
        data.distributePlatId = parseInt(configObj.distributePlatId);
        data.distributeWay = parseInt(configObj.distributeWay);
        if (json.obj.distributeWay == 10) {
            data.provinceName = province.getValue()[0].name;
            data.cityName = city.getValue()[0].name;
        }
        var url = "";

        //distributePlatId为空是新增，先将数据存入缓存；distributePlatId不为空走更新，直接写入数据库
        if(configObj.distributePlatId==null||configObj.distributePlatId==undefined||configObj.distributePlatId==""){
            url = "/orderconfig/distribute/plat/setSendOrderConfigDataToRedis";
            $http.save(url, data).then(function () {
                zmnUtils.layui.toastSuccess('成功', function () {
                    element.tabChange('changeFirstTab', 'repairOrderId');
                })
            }, function (msg) {
                zmnUtils.layui.toastError(msg);
                element.tabChange('changeSecondTab', 'robOrderId');
            });
        }else{
            data.distributePlatId=configObj.distributePlatId;
            data.autoStatusRework= configObj.autoStatusRework;
            data.reworkLimit =configObj.reworkLimit;
            url = "/orderconfig/distribute/plat/modifyOrInsert"
            $http.save(url, data).then(function () {
                zmnUtils.layui.toastSuccess('成功', function () {
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                    window.parent.location.reload();
                })
            }, function (msg) {
                zmnUtils.layui.toastError(msg);
                element.tabChange('changeSecondTab', 'robOrderId');
            });
        }

        return false;
    });

    // 设置完成数据写入数据库
    form.on('submit(zmn-form-submit-to-database)', function (obj) {

        var data = obj.field;
        var robOrderData={};
        data.distributeWay=configObj.distributeWay;
        //目前仅针对啄木鸟平台
        data.plat=10;
        var url ="";
        var robOrderUrl="";
        //distributePlatId为空是新增，先将数据存入缓存；distributePlatId不为空走更新，直接写入数据库
        if(configObj.distributePlatId==null||configObj.distributePlatId==undefined||configObj.distributePlatId==""){
            //判断cityId是否为空，为空说明未设置抢单规则
            if(data.distributeWay==10){
                if(cityId == "" || cityId == undefined || cityId == null){
                    zmnUtils.layui.toastError("请先设置对应城市的抢单规则！");
                    element.tabChange('changeSecondTab', 'robOrderId');
                }
            }

            url = "/orderconfig/distribute/plat/modifyOrInsert";
            robOrderUrl = "/orderconfig/distribute/plat/robOrder/modifyOrInsert";
            data.cityId=cityId;
            data.cityName=cityName;
            robOrderData.cityId=cityId;
            robOrderData.cityName=cityName;
            robOrderData.distributeWay=configObj.distributeWay;
            robOrderData.plat=10;
            $http.save(robOrderUrl, robOrderData).then(function () {
                zmnUtils.layui.toastSuccess('成功', function () {
                    $http.save(url, data).then(function () {
                        zmnUtils.layui.toastSuccess('成功', function () {
                            var index = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(index);
                            window.parent.location.reload();
                        })
                    }, function (msg) {
                        zmnUtils.layui.toastError(msg);
                    });
                })
            }, function (msg) {
                zmnUtils.layui.toastError(msg);
            });
        }else{
            configObj.autoStatusRework=data.autoStatusRework;
            configObj.reworkLimit=data.reworkLimit;
            url = "/orderconfig/distribute/plat/modifyOrInsert";
            $http.save(url, configObj).then(function () {
                zmnUtils.layui.toastSuccess('成功', function () {
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                    window.parent.location.reload();
                })
            }, function (msg) {
                zmnUtils.layui.toastError(msg);
            });
        }

        return false;
    });

    form.on('switch(roundsEnable)', function (data) {
        if (this.checked) {
            // 解除禁用输入框
            $('#nonDirectCount').attr("disabled", false);
            $("#nonDirectCount").removeClass("layui-disabled").prop("disabled", false);
            $('#directSaleCount').attr("disabled", false);
            $("#directSaleCount").removeClass("layui-disabled").prop("disabled", false);
        } else {
            $('#nonDirectCount').attr("disabled", true);
            $("#nonDirectCount").addClass("layui-disabled").prop("disabled", true);
            $('#directSaleCount').attr("disabled", true);
            $("#directSaleCount").addClass("layui-disabled").prop("disabled", true);
        }
    });

// 新单简单派单和新单自动派单，不能同时设置为：关闭；
    form.on('switch(newSimpleStatus)',
        (data) => {
            var checkedValue = $('input[name="autoStatusNew"]:checked').val();
            if (1 == checkedValue) {
                layer.msg("新单简单派单和新单自动派单，不能同时设置为：关闭；");
                $("#newSimpleStatus").prop("checked", true);
                form.render();

            }
            if (3 == checkedValue) {
                layer.msg("当新单自动派单设置为“指定自动派”时，不可将新单简单派单设置为：关闭");
                $("#newSimpleStatus").prop("checked", true);
                form.render();
            }

            // 关闭新单简单派，使新单自动派不能勾选
            if (!data.elem.checked) {
                $("input[name='autoStatusNew'][value='1']").attr("disabled", "disabled");
                $("input[name='autoStatusNew'][value='3']").attr("disabled", "disabled");
                // $("input[name='autoStatusNew'][value='1']").addClass("layui-disabled");
                form.render();
            } else {
                $("input[name='autoStatusNew'][value='1']").removeAttr("disabled");
                $("input[name='autoStatusNew'][value='3']").removeAttr("disabled");
                form.render();
            }

        }
    );

    var timeStr = configObj.autoTimeStart == null ? '07:00 ~ 21:00' : (configObj.autoTimeStart + " ~ " + configObj.autoTimeEnd);

//日期时间范围选择
    laydate.render({
        elem: '#autoTimeStr'
        , type: 'time'
        , range: '~'
        , format: 'HH:mm'
        , value:timeStr
        , trigger: 'click'
    });

    laydate.render({
        elem: '#appointmentTimeStr'
        , type: 'time'
        , range: '~'
        , format: 'HH:mm'
        , trigger: 'click'
    });
    laydate.render({
        elem: '#orderTimeStr'
        , type: 'time'
        , range: '~'
        , format: 'HH:mm'
        , trigger: 'click'
    });
    laydate.render({
        elem: '#robOrderTimeStr'
        , type: 'time'
        , range: '~'
        , format: 'HH:mm'
        , trigger: 'click'
    });

    table.init('zmn-table-1', {
        page: false
    });
    table.on('edit(zmn-table-1)', function (obj) {
        let value = obj.value; // 修改后的值
        let field = obj.field; //得到字段
        configObj.distributeWeightRelationList.forEach(r => {
            if (r.weightType == 1) {
                r[field] = value;
            }
        });
    });

    table.init('zmn-table-2', {
        page: false
    });
    table.on('edit(zmn-table-2)', function (obj) {
        let value = obj.value; // 修改后的值
        let field = obj.field; //得到字段
        /*configObj[field] = value;
        configObj.distributeWeightRelationList[1][field] = value;*/
        configObj.distributeWeightRelationList.forEach(r => {
            if (r.weightType == 2) {
                r[field] = value;
            }
        });
    });

    function dealRobOrderConfigData(data) {

        if (data.configId == undefined || data.configId == "" || data.configId == null) {
            return false;
        }
        let result = {};
        if(data.robOrderRelationList.length>1){
            var result2=data.robOrderRelationList[1];
            var orderTimeData = result2.orderTimeStart == null?'':result2.orderTimeStart+ " ~ "+result2.orderTimeEnd;
            var appointmentTimeData = result2.appointmentTimeStart == null?'':result2.appointmentTimeStart+ " ~ "+result2.appointmentTimeEnd;
            var robOrderTimeData = result2.robOrderTimeStart == null?'':result2.robOrderTimeStart+ " ~ "+result2.robOrderTimeEnd;
            var engineerTypeVal = result2.engineerType;
            var relationId = result2.relationId;
            $("#dynamic").append(initRuleNode(orderTimeData,appointmentTimeData,robOrderTimeData,engineerTypeVal,relationId));
            //最多两条规则
            $("#addRules").hide();
            drawTimePlug();
            if(data.robOrderRelationList!=null&&data.robOrderRelationList[0].robOrderRelationProductList!=null&&data.robOrderRelationList[0].robOrderRelationProductList.length>1){
                $(".productFlag").append(addProductsFunc());
                $(".addProducts").hide();
                drawSelect1();
            };
            //渲染下拉框
            drawSelect('edit');

            if(data.robOrderRelationList!=null&&data.robOrderRelationList[1].robOrderRelationProductList!=null&&data.robOrderRelationList[1].robOrderRelationProductList.length>1){
                $(".productFlag1").append(addProductsFunc1());
                $(".addProducts").hide();
                $(".addProducts1").hide();
                drawSelect3();
            }
        }else{
            if(data.robOrderRelationList!=null&&data.robOrderRelationList.length>0&&data.robOrderRelationList[0].robOrderRelationProductList!=null&&data.robOrderRelationList[0].robOrderRelationProductList.length>1){
                $(".productFlag").append(addProductsFunc());
                $(".addProducts").hide();
                drawSelect1();
            }else{
                $(".addProducts").show();
            }
            $("#addRules").show();
        }


        var result1=data.robOrderRelationList[0];
        if(result1!=undefined&&result1!=""&&result1!=null){
            var orderTimeData = result1.orderTimeStart == null?'':result1.orderTimeStart+ " ~ "+result1.orderTimeEnd;
            var appointmentTimeData = result1.appointmentTimeStart == null?'':result1.appointmentTimeStart+ " ~ "+result1.appointmentTimeEnd;
            var robOrderTimeData = result1.robOrderTimeStart == null?'':result1.robOrderTimeStart+ " ~ "+result1.robOrderTimeEnd;
            result.orderTimeStr =orderTimeData ;
            result.appointmentTimeStr =appointmentTimeData;
            result.robOrderTimeStr = robOrderTimeData;
            result.engineerType = result1.engineerType;
            result.relationId =result1.relationId;
        }
        form.val("zmn-rob-order-form", result);
    }

//对外暴露的接口
    exports('orderconfig_distribute_edit', {});
})
;